package us.codecraft.webmagic.core.downloader.okhttp;


import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

@SuppressWarnings({"Duplicates", "JavaDoc"})
public class OkHttpUtil {
    //private static final String CHARSET_NAME = "UTF-8";
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static final MediaType FILE = MediaType.parse("application/octet-stream");

    /**
     * 同步get
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static Response get(String url, Map<String, String> heads, OkHttpClient okHttpClient) throws Exception {
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if (heads != null) {
            for (Map.Entry<String, String> entry : heads.entrySet()) {
                builder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        Request request = builder.build();
        Response response = execute(request, okHttpClient);
        if (response.isSuccessful()) {
            return response;
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * 同步get请求
     *
     * @param url
     * @param data
     * @return
     * @throws Exception
     */
    public static Response get(String url, Map<String, String> data, Map<String, String> heads, OkHttpClient okHttpClient) throws Exception {
        url = getRequestUrl(url, data);
        return get(url, heads, okHttpClient);
    }

    /**
     * 异步get请求
     *
     * @param url
     * @param responseCallback
     * @return
     * @throws Exception
     */
    public static void get(String url, Callback responseCallback, OkHttpClient okHttpClient) throws Exception {
        get(url, null, null, responseCallback, okHttpClient);
    }

    /**
     * 异步get
     *
     * @param url
     * @param data
     * @param responseCallback
     * @return
     * @throws Exception
     */
    public static void get(String url, Map<String, String> data, Map<String, String> heads, Callback responseCallback, OkHttpClient okHttpClient) {
        url = getRequestUrl(url, data);
        Request.Builder builder = new Request.Builder().url(url);
        if (heads != null) {
            for (Map.Entry<String, String> entry : heads.entrySet()) {
                builder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        enqueue(builder.build(), responseCallback, okHttpClient);
    }

    /**
     * 同步post json数据
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static Response postJson(String url, String json, Map<String, String> heads, OkHttpClient okHttpClient) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request.Builder requestBuild = new Request.Builder().url(url).post(body);
        if (heads != null) {
            for (Map.Entry<String, String> entry : heads.entrySet()) {
                requestBuild.addHeader(entry.getKey(), entry.getValue());
            }
        }
        Response response = execute(requestBuild.build(), okHttpClient);
        if (response.isSuccessful()) {
            return response;
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * 同步post file
     *
     * @param url
     * @param path
     * @param paramMap
     * @return
     */
    public static Response postFile(String url, String path, Map<String, String> paramMap, OkHttpClient okHttpClient) throws IOException {
        File file = new File(path);
        RequestBody fileBody = RequestBody.create(FILE, file);
        MultipartBody.Builder multBuilder = new MultipartBody.Builder();
        multBuilder.setType(MultipartBody.ALTERNATIVE);
        //一般参数
        if (paramMap != null) {
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                multBuilder.addFormDataPart(entry.getKey(), entry.getValue());
            }
        }
        MultipartBody multipartBody = multBuilder
                .addPart(Headers.of("Content-Disposition", "form-data; name=\"file\"; filename=" + file.getName() + ""), fileBody)
                .build();
        Request request = new Request.Builder().url(url).post(multipartBody).build();
        Response response = execute(request, okHttpClient);
        if (response.isSuccessful()) {
            return response;
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * 同步post 键值对数据
     *
     * @param url
     * @param data
     * @return
     * @throws IOException
     */
    public static Response postForm(String url, Map<String, String> data, Map<String, String> heads, OkHttpClient okHttpClient) throws IOException {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> item : data.entrySet()) {
            builder.add(item.getKey(), item.getValue());
        }

        RequestBody body = builder.build();
        Request.Builder requestbuild = new Request.Builder();
        requestbuild.url(url).post(body);
        if (heads != null) {
            for (Map.Entry<String, String> entry : heads.entrySet()) {
                requestbuild.addHeader(entry.getKey(), entry.getValue());
            }
        }
        Response response = execute(requestbuild.build(), okHttpClient);
        if (response.isSuccessful()) {
            return response;
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * 异步post json
     *
     * @param url
     * @param json
     * @param responseCallback
     * @throws IOException
     */
    public static void post(String url, String json, Callback responseCallback,Map<String, String> heads, OkHttpClient okHttpClient) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request.Builder requestbuild = new Request.Builder();
        if (heads != null) {
            for (Map.Entry<String, String> entry : heads.entrySet()) {
                requestbuild.addHeader(entry.getKey(), entry.getValue());
            }
        }
        Request request =requestbuild.url(url).post(body).build();
        enqueue(request, responseCallback, okHttpClient);
    }

    /**
     * 异步post key-value
     *
     * @param url
     * @param data
     * @param responseCallback
     * @throws IOException
     */
    public static void post(String url, Map<String, String> data, Map<String, String> heads, Callback responseCallback, OkHttpClient okHttpClient) {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> item : data.entrySet()) {
            builder.add(item.getKey(), item.getValue());
        }

        RequestBody body = builder.build();
        Request.Builder requestbuild = new Request.Builder();
        requestbuild.url(url).post(body);
        if (heads != null) {
            for (Map.Entry<String, String> entry : heads.entrySet()) {
                requestbuild.addHeader(entry.getKey(), entry.getValue());
            }
        }
        enqueue(requestbuild.build(), responseCallback, okHttpClient);
    }

    /**
     * 同步put
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static String put(String url, String json, OkHttpClient okHttpClient) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);

        Request request = new Request.Builder().url(url).put(body).build();

        Response response = execute(request, okHttpClient);
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * 同步put key-value
     *
     * @param url
     * @param data
     * @return
     * @throws IOException
     */
    public static String put(String url, Map<String, String> data, OkHttpClient okHttpClient) throws IOException {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> item : data.entrySet()) {
            builder.add(item.getKey(), item.getValue());
        }

        RequestBody body = builder.build();
        Request request = new Request.Builder().url(url).put(body).build();

        Response response = execute(request, okHttpClient);
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * 异步put json
     *
     * @param url
     * @param json
     * @throws IOException
     */
    public static void put(String url, String json, Callback responseCallback, OkHttpClient okHttpClient) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);

        Request request = new Request.Builder().url(url).put(body).build();
        enqueue(request, responseCallback, okHttpClient);
    }

    /**
     * 异步put key-value
     *
     * @param url
     * @param data
     * @param responseCallback
     * @throws IOException
     */
    public static void put(String url, Map<String, String> data, Callback responseCallback, OkHttpClient okHttpClient) throws IOException {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> item : data.entrySet()) {
            builder.add(item.getKey(), item.getValue());
        }

        RequestBody body = builder.build();
        Request request = new Request.Builder().url(url).put(body).build();

        enqueue(request, responseCallback, okHttpClient);
    }

    /**
     * 通用同步请求。
     *
     * @param request
     * @return
     * @throws IOException
     */
    private static Response execute(Request request, OkHttpClient okHttpClient) throws IOException {
        return okHttpClient.newCall(request).execute();
    }

    /**
     * 通用异步请求
     *
     * @param request
     * @param responseCallback
     */
    private static void enqueue(Request request, Callback responseCallback, OkHttpClient okHttpClient) {
        okHttpClient.newCall(request).enqueue(responseCallback);
    }

    /**
     * 开启异步线程访问网络, 且不在意返回结果（实现空callback）
     *
     * @param request
     */
    private static void enqueue(Request request, OkHttpClient okHttpClient) {
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });
    }

    public static String getStringFromServer(String url, OkHttpClient okHttpClient) throws IOException {
        Request request = new Request.Builder().url(url).build();
        Response response = execute(request, okHttpClient);
        if (response.isSuccessful()) {
            if(response.body() != null){
                return response.body().string();
            }
            return "";
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }


    /**
     * get方式URL拼接
     *
     * @param url
     * @param map
     * @return
     */
    private static String getRequestUrl(String url, Map<String, String> map) {
        if (map == null || map.size() == 0) {
            return url;
        } else {
            StringBuilder newUrl = new StringBuilder(url);
            if (!url.contains("?")) {
                newUrl.append("?rd=").append(Math.random());
            }

            for (Map.Entry<String, String> item : map.entrySet()) {
                try {
                    String param = "&" + item.getKey().trim() + "=" + URLEncoder.encode(item.getValue().trim(),"UTF-8");
                    newUrl.append(param);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            return newUrl.toString();
        }
    }
}